<template>
    <el-dialog v-model="dialogVisible" :align-center="true" title="收银系统" width="700px" height="600px" @close="handleClose">
        <el-table :data="selectList" row-key="id" max-height="500" style="flex:1">
            <el-table-column label="商品" align="left" prop="skuName" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column label="单价" align="left" prop="unitPrice" width="80"></el-table-column>
            <el-table-column label="会员价" prop="salePrice" width="80"></el-table-column>
            <el-table-column label="数量">
                <template #default="scope">
                    <el-input-number v-model="scope.row.skuCount" :min="0"/>
                </template>
            </el-table-column>
        </el-table>

        <div class="row sumary">
            <text class="price">共计: {{totalCount}}件商品</text>
            <text class="price">原价：￥{{originalFee}}</text>
            <text class="price">优惠：￥{{parseInt(originalFee-totalFee)}}</text>
            <text class="price">合计:￥{{totalFee}}</text>
        </div>
        <div class="action-box row">
            <el-input placeholder="输入会员手机号，回车查询" v-model="phone" style="width: 300px"></el-input>
            <el-button @click="searchCustomer">选择会员</el-button>
            <text v-if="customer" class="customer" @click="removeCustomer">{{customer.nickName}}</text>
            <el-button type="primary" @click="pay(0)">下单</el-button>
        </div>
        <div class="action-box row">
            <text>线下收款：</text>
            <el-button @click="pay(1)" type="success" size="small">微信</el-button>
            <el-button @click="pay(2)" type="success" size="small">支付宝</el-button>
            <el-button @click="pay(3)" type="success" size="small">现金</el-button>
            <el-button @click="pay(4)" type="success" size="small">刷卡</el-button>
            <el-button @click="pay(5)" type="success" size="small">组合</el-button>
        </div>
        <!-- <el-input v-model="scanCode" @keyup.native="concludeData" plcaceholder="聚焦后扫码"></el-input> -->
    </el-dialog>
</template>

<script setup>

import { ElMessage, ElMessageBox } from 'element-plus';

import OrderAPI from '@/api/order';
import UserApi from '@/api/user';
import { computed } from 'vue';

const emit = defineEmits(["update:visible", "onPayBack"])
const props = defineProps({
    visible: { type: Boolean, default: false },
    selectList: { type: Array, default: [] }
})

let dialogVisible = computed({
    get: () => props.visible,
    set: (val) => {
        emit("update:visible", val);
    }
})

let totalFee = computed({
    get: ()=> {
        let skuList = props.selectList
        return skuList.reduce((total, curr)=>{
            if(customer.value.id == 0){
                return (total*100 + curr.skuCount*curr.unitPrice*100)/100
            } else {
                return (total*100 + curr.skuCount*curr.salePrice*100)/100
            }
        }, 0)
    }
})
let originalFee = computed({
    get: ()=> {
        let skuList = props.selectList
        return skuList.reduce((total, curr)=>{
            return (total*100 + curr.skuCount*curr.unitPrice*100)/100
        }, 0)
    }
})
let totalCount = computed({
    get: ()=> {
        let skuList = props.selectList
        return skuList.reduce((total, curr)=>{
            return (total*100 + curr.skuCount*100)/100
        }, 0)
    }
})
let customer = ref({id:0, nickName: "无会员"})
let phone = ref("")
function searchCustomer(){
    UserApi.searchUser(1, phone.value).then(users=>{
        if(users.length>0){
            customer.value = users[0]
            const customerId = customer.value.id
            props.selectList.forEach(i=>{
                i.salePrice = customerId==0?i.unitPrice:i.salePrice
            })
        }
    })
}
function getSkuList(customerId){
    return props.selectList.map(i=>{
        let salePrice = customerId==0?i.unitPrice:i.salePrice
        return {
            unitPrice: parseInt(i.unitPrice*100),
            salePrice: parseInt(salePrice*100),
            skuCount: i.skuCount,
            skuId: i.skuId,
            skuName: i.skuName
        }
    })
}
let barCode = ""
let waitPayOrder = null
window.addEventListener('keydown', function(event){
    console.log("扫码:", event)
    if (event.key !== "Enter"){ // 回车代表结束
        barCode += event.key
    } else {
        // 清除输入缓冲区，防止其他按键事件的干扰
        console.log("scan_code_result", barCode)
        OrderAPI.payOrder(barCode, waitPayOrder.orderNo, waitPayOrder.amount).then(res=>{
            ElMessage.success("支付成功！")
            barCode = ""
            emit("onPayBack", res)
        }).catch(e=>{
            barCode = ""
            ElMessage.error("支付失败！", e)
        })
    }
}, true);

function pay(type){
    const customerId = customer.value.id
    let order = {shopId:1, employeeId:4, customerId, payType: type, skuList: getSkuList(customerId)}
    OrderAPI.createOrder(order).then(res=>{
        waitPayOrder = res
        barCode = ""
        ElMessage.success("下单成功，等待扫码支付！");
        ElMessageBox.confirm(
            '请使用扫码设备扫描用户付款码！',
            '等待支付',
            {type: 'warning',draggable: true,overflow: true}
        ).then(()=>{
            dialogVisible.value = false
        }).catch(()=>{
            dialogVisible.value = false
        })
    })
}

function removeCustomer(){
    customer.value = {id:0, nickName: "无会员"}
}
</script>

<style>
.action-box{
    margin: 12px;
}
.row{
    display: flex;
    flex-direction: row;
}
.sumary{
    width: 100%;
    margin: 12px;
    text-align: end;
}
.price{
    margin: 0 12px;
}
.customer{
    border: 1px solid rgb(251, 205, 3);
    padding: 4px 12px;
    border-radius: 8px;
    margin: 0 24px;
}
</style>